/*jslint vars:true plusplus:true devel:true*/

//=========================================================
// Interactive Digital Media Diploma
// CUFDIG404A_R1: Introduction to Scripting
// Assignment 3
// Author: Ben
// File: entity.js
// Description: initialize and update all subsystems
//=========================================================


// core game object
function Game() {
    "use strict";
    
    // retain reference to self for events
    var self = this;
    
    // all of the subsystems of the game
    var subSystems = [];
    
    // the game frame refresh rate
    self.frameRate = 30;
    self.canvas = document.getElementById("myCanvas");
    self.context = self.canvas.getContext("2d");
    self.showDebug = true;
    self.onClick = function(){};
    // add a new subsystem
    this.addSubsystem = function (subSystem) {
        if (subSystem) {
            subSystems.push(subSystem);
            if (subSystem.init) {
                subSystem.init();
            }
        } else {
            console.log("Attempting to add undefined subsystem to game");
        }
    };
    
    
    // update and draw every frame
    this.update = function () {
        
        // update all subsystems
        var systemIdx;
        for (systemIdx = 0; systemIdx < subSystems.length; systemIdx++) {
            if (subSystems[systemIdx].update) {
                subSystems[systemIdx].update();
            }
        }
            
        // draw all subsystems
        for (systemIdx = 0; systemIdx < subSystems.length; systemIdx++) {
            if (subSystems[systemIdx].draw) {
                subSystems[systemIdx].draw(self.context);
            }
        }
        if (self.showDebug) {
            // debug draw all subsystems
            for (systemIdx = 0; systemIdx < subSystems.length; systemIdx++) {
                if (subSystems[systemIdx].debugdraw) {
                    subSystems[systemIdx].debugdraw(self.context);
                }
            }
        }
    };

    // updated keystates
    this.setKeyVal = function (keyCode, value) {
        var systemIdx;
        for (systemIdx = 0; systemIdx < subSystems.length; systemIdx++) {
            if (subSystems[systemIdx].keyVal) {
                subSystems[systemIdx].keyVal(keyCode, value);
            }
        }
    };
    
    // respond to key presses
    document.onkeydown = function (evt) {
        self.setKeyVal(evt.keyCode, 1);
    };

    document.onkeyup = function (evt) {
        self.setKeyVal(evt.keyCode, 0);
    };

    document.addEventListener("click", function(event){
        self.onClick(event);
    });
    
    // set up frame updates
    setInterval(self.update, self.frameRate);

}


window.game = new Game();

//audio
